package dbs

import (
	"ManageServer/utils/currenttime"
	"fmt"
	"github.com/golang-module/carbon"
	"github.com/jinzhu/gorm"
	"time"
)

type DbStaffRecord struct {
	ID               uint      `json:"id" gorm:"primary_key"`
	StaffId          uint      `json:"staff_id" gorm:"index"`                           // 职工ID
	StaffHash        string    `json:"staff_hash" gorm:"type:varchar(64)"`              // 职工的人脸hash
	StaffIc          string    `json:"staff_ic" gorm:"type:varchar(64)"`                // 职工的ic卡号
	StaffAttachments string    `json:"staff_attachments" gorm:"type:varchar(256)"`      // 职工附件
	Status           string    `json:"status" gorm:"type:varchar(32);default:'';index"` // 状态
	EffectiveTime    time.Time `json:"effective_time" gorm:"type:datetime"`             // 有效时间
	CreatedBy        string    `json:"created_by" gorm:"type:varchar(64)"`              // 创建人
	ReviewBy         string    `json:"review_by" gorm:"type:varchar(64)"`               // 审核人
	RecordType       string    `json:"record_type" gorm:"type:varchar(32)"`             // 日志类型  职工  第三方职工
	ReviewAt         time.Time `json:"review_at" gorm:"type:datetime"`                  // 审核时间
	CreatedAt        time.Time `json:"created_at" gorm:"type:datetime"`
	UpdatedAt        time.Time `json:"updated_at" gorm:"type:datetime"`
}
type DbStaffRecordCheckName struct {
	Name string `json:"name"` //职工姓名
}
type DbStaffRecordCreate struct {
	StaffId          uint   `json:"staff_id"`                   // 职工id
	Name             string `json:"name"`                       // 姓名
	Gender           string `json:"gender"`                     // 性别
	Phone            string `json:"phone" validate:"required" ` // 手机号
	Role             string `json:"role"`                       // 角色：超管 管理员、职工  患陪
	RecordType       string `json:"record_type"`
	StaffAttachments string `json:"staff_attachments"` // 职工附件
	Department       string `json:"department"`        // 科室
	StaffIc          string `json:"staff_ic"`          // 职工的ic卡号
	StaffHash        string `json:"staff_hash"`        // 职工的人脸hash
	CreatedBy        string `json:"created_by"`        // 创建人
}

type DbStaffRecordUpdate struct {
	StaffId      uint   `json:"staff_id"` // 职工id
	Name         string `json:"name"`     // 姓名
	Phone        string `json:"phone"`    // 手机号
	Hash         string `json:"hash"`
	ToUpdateHash string `json:"to_update_hash"`
}

type DbStaffRecordList struct {
	ID              uint      `json:"id"`         // 授权编号
	Name            string    `json:"name"`       // 姓名
	Gender          string    `json:"gender"`     // 性别
	Phone           string    `json:"phone"`      // 手机号
	Department      string    `json:"department"` // 科室
	Role            string    `json:"role"`
	RecordType      string    `json:"record_type"`
	CreatedBy       string    `json:"created_by"` // 创建人
	StaffId         uint      `json:"staff_id"`
	Status          string    `json:"status"`          // 状态
	EffectiveTime   time.Time `json:"effective_time"`  // 有效时间
	CreatedAt       time.Time `json:"created_at"`      // 创建时间时间
	CreateTimeStart string    `json:"CreateTimeStart"` //
	CreateTimeEnd   string    `json:"CreateTimeEnd"`   //
	Event           int       `json:"event"`
	Page            int       `json:"page" label:"页数"`
	Limit           int       `json:"limit" label:"每页显示数"`
	Order           string    `json:"order" `
}

type DbStaffRecordGet struct {
	ID       uint   `json:"id"` // 授权编号
	StaffId  uint   `json:"staff_id"`
	Status   string `json:"status"`
	ReviewBy string `json:"review_by"` //审核人
}

type DbStaffRecordGetTo struct {
	ID               uint      `json:"id"`                // 授权编号
	Name             string    `json:"name"`              // 姓名
	StaffId          uint      `json:"staff_id"`          // userID
	Gender           string    `json:"gender"`            // 性别
	Phone            string    `json:"phone"`             // 手机号
	Department       string    `json:"department"`        // 科室
	StaffIc          string    `json:"staff_ic"`          // 职工的ic卡号
	StaffAttachments string    `json:"staff_attachments"` // 职工附件
	Status           string    `json:"status"`            // 状态
	StaffHash        string    `json:"staff_hash"`        //人脸hash
	CreatedBy        string    `json:"created_by"`        // 创建人
	CreatedAt        time.Time `json:"created_at"`        // 申请时间
	ReviewBy         string    `json:"review_by"`         // 审核人
	TmeshId          string    `json:"tmesh_id"`          // 审核时间
	ReviewAt         time.Time `json:"review_at"`         // 审核时间
	EffectiveTime    time.Time `json:"effective_time"`    //有效时间
}

type DbStaffRecordCheckTo struct {
	Name       string `json:"name"`       // 姓名
	Gender     string `json:"gender"`     // 性别
	Phone      string `json:"phone"`      // 手机号
	Department string `json:"department"` // 科室
}

func (self *DbStaffRecord) Create() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Create(&self).Error
	})
	return
}

func (self *DbStaffRecord) Exist() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if self.StaffId != 0 {
			conn = conn.Where("staff_id = ? ", self.StaffId)
		}

		if self.Status != "" {
			conn = conn.Where("status = ? ", self.Status)
		}

		if self.StaffHash != "" {
			conn = conn.Where("staff_hash = ? ", self.StaffHash)
		}

		if self.ID != 0 {
			conn = conn.Where("id <> ? ", self.ID)
		}

		return conn.First(&self).Error
	})
	return
}

func (self *DbStaffRecord) SearchCount(s_list DbStaffRecordList) (number int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		if s_list.Department != "" {
			conn = conn.Where("db_users.department = ?", s_list.Department)
		}
		conn = conn.Where("db_staff_records.record_type = ?", "第三方职工")

		if s_list.Status != "" {
			conn = conn.Where("db_staff_records.status = ?", s_list.Status)
		}
		return conn.Model(&self).Joins(" left join `db_users` on db_users.id = db_staff_records.staff_id").Count(&number).Error
	})
	return
}
func (self *DbStaffRecord) SearchStaffCount(s_list DbStaffRecordList) (number int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		if s_list.Department != "" {
			conn = conn.Where("db_users.department = ?", s_list.Department)
		}
		if self.Status != "" {
			conn = conn.Where("db_staff_records.status = ?", self.Status)
		}
		return conn.Model(&self).Where("db_staff_records.record_type = ?", "职工").Joins(" left join `db_users` on db_users.id = db_staff_records.staff_id").Count(&number).Error
	})
	return
}

func (self *DbStaffRecord) listQuery(conn *gorm.DB, s_list DbStaffRecordList) *gorm.DB {
	datetimeStart, _ := currenttime.StrToTime("2006-01-02 15:04:05", s_list.CreateTimeStart)
	datetimeEnd, _ := currenttime.StrToTime("2006-01-02 15:04:05", s_list.CreateTimeEnd)

	if s_list.Department != "" {
		conn = conn.Where("db_users.department = ?", s_list.Department)
	}

	if s_list.StaffId > 0 {
		conn = conn.Where("db_staff_records.staff_id = ?", s_list.StaffId)
	}

	if s_list.RecordType != "" {
		conn = conn.Where("db_staff_records.record_type = ?", s_list.RecordType)
	}

	if s_list.Role != "" {
		conn = conn.Where("db_users.role = ?", s_list.Role)
	}

	if s_list.Name != "" {
		conn = conn.Where("db_users.name like ?", s_list.Name)
	}

	if s_list.Phone != "" {
		conn = conn.Where("db_users.phone like ?", s_list.Phone)
	}

	if s_list.CreatedBy != "" {
		conn = conn.Where("db_staff_records.created_by = ?", s_list.CreatedBy)
	}

	if s_list.CreateTimeStart != "" && s_list.CreateTimeEnd != "" {
		conn = conn.Where("db_staff_records.created_at between ? and ? ", datetimeStart, datetimeEnd)
	}
	if s_list.Gender != "" {
		conn = conn.Where("db_users.gender = ?", s_list.Gender)
	}
	if s_list.Status != "" {
		conn = conn.Where("db_staff_records.status = ?", s_list.Status)
	}
	return conn
}

//check
//TODO 如何返回
func (self *DbStaffRecord) Query(s_list DbStaffRecordList) (staff_list []DbStaffRecordList, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		conn = self.listQuery(conn, s_list)
		// 分页
		if s_list.Page != 0 && s_list.Limit != 0 {
			conn = conn.Offset((s_list.Page - 1) * s_list.Limit).Limit(s_list.Limit)
		}

		if s_list.Order != "" {
			conn = conn.Order(s_list.Order)
		} else {
			conn = conn.Order("id DESC")
		}

		conn = conn.Model(&self).Select("db_staff_records.id,db_staff_records.effective_time,db_users.name,db_users.phone,db_users.gender,db_staff_records.created_at as created_at,db_users.department,db_staff_records.created_by,db_staff_records.status,db_staff_records.created_at").Joins(" left join" +
			" `db_users` on db_users.id = db_staff_records.staff_id").Scan(&staff_list)
		err = conn.Error
		return
	})

	fmt.Println("staff_liststaff_list  !!! ", staff_list)
	return
}

func (self *DbStaffRecord) Get(id uint) (result DbStaffRecordGetTo, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		return conn.Model(&DbStaffRecord{}).Select("db_staff_records.id,db_users.name,db_users.gender,db_users.phone,db_users.department,db_staff_records.created_by,"+
			"db_staff_records.created_at,db_staff_records.staff_id,db_staff_records.staff_ic,db_staff_records.review_by,db_staff_records.staff_attachments,db_staff_records.effective_time,db_staff_records.review_at,db_staff_records.staff_hash,db_staff_records.id,db_staff_records.status,db_users.tmesh_id").Joins("left join db_users on "+
			"db_staff_records.staff_id = db_users.id").Where("db_staff_records.id = ?", id).Scan(&result).Error
	})
	return
}

func (self DbStaffRecord) GetByStaff(id uint) (result DbStaffRecordGetTo, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		conn = conn.Model(&self).Select("db_staff_records.id,db_users.name,db_users.gender,db_users.phone,db_users.department,db_staff_records.created_by,"+
			"db_staff_records.created_at,db_staff_records.staff_ic,db_staff_records.review_by,db_staff_records.review_at,db_staff_records.staff_hash,db_staff_records.id,db_staff_records.status").Joins("left join db_users on "+
			"db_staff_records.staff_id = db_users.id").Where("db_staff_records.staff_id = ?", id).Scan(&result)
		return
	})
	return
}

func (self *DbStaffRecord) Count(s_list DbStaffRecordList) (count int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if s_list.Name != "" {
			conn = conn.Where("name like ?", s_list.Name)
		}

		return conn.Model(&self).Count(&count).Error
	})
	return
}

func (self *DbStaffRecord) CountList(s_list DbStaffRecordList) (number int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		conn = self.listQuery(conn, s_list)

		conn = conn.Model(&self).Joins(" left join `db_users` on db_users.id = db_staff_records.staff_id").Count(&number)
		err = conn.Error
		return
	})

	return

}

func (self *DbStaffRecord) Update(params map[string]interface{}) (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Model(&self).Update(params).Error
	})
	return
}

func (self *DbStaffRecord) UpdateRaw(db *gorm.DB, params map[string]interface{}) (err error) {
	return db.Model(&self).Update(params).Error
}

func (self *DbStaffRecord) UpdateBatchByStaffId(params map[string]interface{}) (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		return conn.Model(&DbStaffRecord{}).Where("staff_id = ?", self.StaffId).Update(params).Error
	})
	return
}

func (self DbStaffRecord) GetRecord(params DbStaffRecordGet) (result DbStaffRecord, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		if params.ID > 0 {
			conn = conn.Where("id = ?", params.ID)
		}
		if params.StaffId > 0 {
			conn = conn.Where("staff_id = ?", params.StaffId)
		}

		if params.Status != "" {
			conn = conn.Where("status = ?", params.Status)
		}

		if params.ReviewBy != "" {
			conn = conn.Where("review_by = ?", params.ReviewBy)
		}

		err = conn.First(&result).Error
		return
	})
	return
}

func (self *DbStaffRecord) GetOperateRecord() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if self.StaffId > 0 {
			conn = conn.Where("staff_id = ?", self.StaffId)
		}

		conn = conn.Where("status NOT IN (?)", []string{
			"已拒绝", "已失效",
		})

		err = conn.First(&self).Error
		return
	})
	return
}

func (self *DbStaffRecord) CheckImg() (result DbStaffRecord, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if self.StaffHash != "" {
			conn = conn.Where("staff_hash = ? and staff_id != ?", self.StaffHash, self.StaffId)
		}

		err = conn.Find(&result).Error
		return
	})
	fmt.Println("self   ! ", self)
	return
}

func (self DbStaffRecord) CheckTime() (result int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		conn = conn.Model(&self).Where("staff_id = ? and effective_time > ? ", self.StaffId, carbon.Now().ToDateTimeString()).Count(&result)
		return
	})
	fmt.Println("check time :  ", result)
	return
}

func (self *DbStaffRecord) Save() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		return conn.Save(&self).Error
	})
	return
}

func (c *DbStaffRecord) Format() (result map[string]interface{}) {
	result = map[string]interface{}{
		"id":                c.ID,
		"staff_id":          c.StaffId,
		"staff_hash":        c.StaffHash,
		"staff_ic":          c.StaffIc,
		"staff_attachments": c.StaffAttachments,
		"status":            c.Status,
		"effective_time":    c.EffectiveTime.Format("2006-01-02 15:04:05"),
		"created_by":        c.CreatedBy,
		"review_by":         c.ReviewBy,
		"record_type":       c.RecordType,
		"review_at":         c.ReviewAt.Format("2006-01-02 15:04:05"),
		"created_at":        c.CreatedAt.Format("2006-01-02 15:04:05"),
		"update_at":         c.UpdatedAt.Format("2006-01-02 15:04:05"),
	}
	return
}

func (self DbStaffRecord) GetApprovalInValidList() (result []DbStaffRecord, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		return conn.Model(&self).Where(fmt.Sprintf("status = '已通过' and effective_time <= '%s' ", carbon.Now().ToDateTimeString())).Limit(20).Find(&result).Error
	})
	return
}
